﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mads.CoreDomain;

namespace MADSite
{
  public partial class Tickets2 : System.Web.UI.Page
  {
    TrainManagerClient client = new TrainManagerClient();
    int id;
    FreeTicket[] tickets;
    CarType[] types;
    Station stationDep;
    Station stationArr;
    Station[] massiveOfStations;

    TrainManagerClient trainManagerClient = new TrainManagerClient();
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Request.Cookies.AllKeys.Contains("id"))
      {
        id = trainManagerClient.InitUser();
      }
      else
      {
        id = Int32.Parse(Request.Cookies["id"].Value);
      }
      HttpCookie cookie = new HttpCookie("id", id.ToString());
      Response.Cookies.Add(cookie);
      DateTime depTime;
      try
      {
        depTime = DateTime.Parse(Request.Cookies["date"].Value);
      }
      catch (Exception)
      {
        //HACK - should have returned an error
        depTime = DateTime.UtcNow;
      }

      massiveOfStations = client.GetStations(id);
      string depN = Request.Cookies["startPoint"].Value;
      string arrN = Request.Cookies["finishPoint"].Value;
      stationArr = massiveOfStations.FirstOrDefault(x => x.Name == arrN);
      stationDep = massiveOfStations.FirstOrDefault(x => x.Name == depN);

      types = trainManagerClient.GetCarTypes(id);
      wagonType.Items.Clear();
      foreach (CarType type in types)
      {
        wagonType.Items.Add(type.Name);
      }
      tickets = client.GetTickets(id, depTime, stationDep, stationArr);

      routeTextBox.Text = String.Empty;

      var ticketsGrouped =
        tickets.GroupBy(x => new
        {
          Route = x.RouteNumber,
          Car = x.CarNumber,
          Departure = x.DepartureTime
        }).Select(group => group.First());

      foreach (FreeTicket ticket in ticketsGrouped)
      {
        routeTextBox.Text += GenerateInfo(ticket) + "\n";
        routeTextBox.Text += "-----------------------\n";
      }
    }

    /// <summary>
    /// Генерим строку вывода данных
    /// </summary>
    /// <param name="ticket">билет</param>
    /// <returns></returns>
    private string GenerateInfo(FreeTicket ticket)
    {
      return String.Format(
        "Маршрут № {0}, тип вагона {1}, отправление {2} в {3}, прибытие {4} в {5}",
        ticket.RouteNumber, ticket.Type.Name,
        ticket.DepartureTime.ToShortDateString(),
        ticket.DepartureTime.ToShortTimeString(),
        ticket.ArrivalTime.ToShortDateString(),
        ticket.ArrivalTime.ToShortTimeString());
    }

    /// <summary>
    /// Перейти к выбору мест
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void nextButton_Click(object sender, EventArgs e)
    {
      string numberString = string.Empty;
      string routeString = raceBox.Text;
      string typeString = wagonType.Text;
      string placeString = sitType.Text;
      foreach (FreeTicket ticket in tickets)
      {
        if (placeString == "Верхнее")
        {
          if (ticket.Type.Name == typeString && ((ticket.SitNumber % 2) == 0) && ticket.RouteNumber == UInt32.Parse(routeString))
          {
            numberString += ticket.SitNumber.ToString() + " ";
          }
        }
        else
        {
          if (ticket.Type.Name == typeString && ((ticket.SitNumber % 2) == 1) && ticket.RouteNumber == UInt32.Parse(routeString))
          {
            numberString += ticket.SitNumber.ToString() + " ";
          }
        }
      }
      if (numberString == "")
      {
        numberString = "к сожалению, подходящих билетов не найдено";
      }

      // Куки списка билетов
      HttpCookie ticketCookie = new HttpCookie("ticket");
      ticketCookie.Value = numberString;
      ticketCookie.Expires = DateTime.Now.AddDays(1);
      Response.Cookies.Add(ticketCookie);

      Response.Redirect("Tickets3.aspx");
    }

    /// <summary>
    /// Вернуться к выбору станций
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void prevButton_Click(object sender, EventArgs e)
    {
      Response.Redirect("Tickets.aspx");
    }

    protected void wagonType_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
  }
}